package com.htx.zqs.blesmartmask.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.BeforeCourseData;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.broadcastreceiver.BleBroadcastReceiver;
import com.htx.zqs.blesmartmask.broadcastreceiver.NetworkReceiver;
import com.htx.zqs.blesmartmask.eventbus.MessageEvent;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.BleUtils;
import com.htx.zqs.blesmartmask.utils.CameraUtil;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.kaopiz.kprogresshud.KProgressHUD;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * Created by zhao on 2018/5/12.
 */

public class TestWaterActivity extends BaseActivity {
    public static final String INSERT_BEFAT = "insertbefattwo.link";
    @InjectView(R.id.waterIamgeView)
    ImageView waterIamgeView;
    @InjectView(R.id.waterTextView)
    TextView waterTextView;
    @InjectView(R.id.oilImageView)
    ImageView oilImageView;
    @InjectView(R.id.oilTextView)
    TextView oilTextView;
    @InjectView(R.id.testButton)
    Button testButton;
    @InjectView(R.id.ib_back)
    ImageButton ibBack;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.ib_menu)
    TextView ibMenu;
    @InjectView(R.id.maskButton)
    Button mMaskButton;

    private ArrayList<Double> mTestData;
    private KProgressHUD mKProgressHUD;
    private BleBroadcastReceiver receiver;
    private AlertDialog.Builder builder;
    private CameraUtil cameraUtil;
    private Dialog mCameraDialog;
    private OkhttpUtils mOkhttpUtils;
    private File mTempFile;
    private String deviceId;
    private String mLastCourseName;
    private int mLimitCourseCount;
    private BleDevice mBleDevice;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_water);
        ButterKnife.inject(this);
        mBleDevice = getIntent().getParcelableExtra(Constants.BLE_DEVICE);
        initView();
    }


    private void showCameraDialog() {
        cameraUtil = new CameraUtil();
        mCameraDialog = cameraUtil.getCameraDialog(this, btnlistener, R.layout.layout_camera_test_water, 0);

    }

    private void initView() {
        if (BlEUtile.checkCameraPermission(this)) {
            showCameraDialog();
        } else {
            new android.support.v7.app.AlertDialog.Builder(this).setTitle(R.string.permission_error_title)
                    .setMessage(R.string.permission_error_message)
                    .setPositiveButton(R.string.cancle, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                            }
                        }
                    })
                    .show();
        }
        deviceId = LocationUtil.getUniquePsuedoID();
        // tvTitle.setVisibility(View.GONE);
        ibBack.setVisibility(View.VISIBLE);
        mKProgressHUD = BlEUtile.getmKProgressHUD(TestWaterActivity.this);
        receiver = new BleBroadcastReceiver(TestWaterActivity.this);
        registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (permissions[0].equals(Manifest.permission.CAMERA)) {
                showCameraDialog();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mKProgressHUD.isShowing()) {
            mKProgressHUD.dismiss();
        }
        BlEUtile.setNull();
        unregisterReceiver(receiver);
        BleUtils.stopNotify(mBleDevice);
    }

    private int getIamgeResource(int data, boolean isWater) {
        if (isWater) {
            if (data < 20) {
                return R.mipmap.blue10;
            } else if (data < 30) {
                return R.mipmap.blue20;
            } else if (data < 40) {
                return R.mipmap.blue30;
            } else if (data < 50) {
                return R.mipmap.blue40;
            } else if (data < 60) {
                return R.mipmap.blue50;
            } else if (data < 70) {
                return R.mipmap.blue60;
            } else if (data < 80) {
                return R.mipmap.blue70;
            } else if (data < 90) {
                return R.mipmap.blue80;
            } else if (data < 100) {
                return R.mipmap.blue90;
            } else {
                return R.mipmap.blue100;
            }

        } else {
            if (data < 20) {
                return R.mipmap.orange10;
            } else if (data < 30) {
                return R.mipmap.orange20;
            } else if (data < 40) {
                return R.mipmap.orange30;
            } else if (data < 50) {
                return R.mipmap.orange40;
            } else if (data < 60) {
                return R.mipmap.orange50;
            } else if (data < 70) {
                return R.mipmap.orange60;
            } else if (data < 80) {
                return R.mipmap.orange70;
            } else if (data < 90) {
                return R.mipmap.orange80;
            } else if (data < 100) {
                return R.mipmap.orange90;
            } else {
                return R.mipmap.orange100;
            }
        }

    }

    private HashMap mMap1 = new HashMap();

    private Handler handler = new Handler();


    private View.OnClickListener btnlistener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_open_camera: // 打开照相机
                    mTempFile = cameraUtil.useCamera(TestWaterActivity.this, 1);
                    break;
                // 打开相册
                case R.id.btn_choose_img:
                    //单选
                    ImageSelector.builder()
                            .useCamera(true) // 设置是否使用拍照
                            .setSingle(true)  //设置是否单选
                            .setViewImage(true) //是否点击放大图片查看,，默认为true
                            .start(TestWaterActivity.this, 551); // 打开相册
                    break;
                // 取消
                case R.id.btn_start_Course:
                    if (mCameraDialog != null) {//10:A2:4E:05:01:25
                        mCameraDialog.dismiss();
                    }
                    mKProgressHUD.setLabel(getResources().getString(R.string.testing)).show();

                    testWater();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mKProgressHUD.isShowing()) {
                                mKProgressHUD.dismiss();
                            }
                        }
                    }, 7000);
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == Contants.CAMERA_REQUEST_CODE) { //调用相机后返回
            if (resultCode == RESULT_OK) {
                //用相机返回的照片去调用剪裁也需要对Uri进行处理
                CameraUtil.flushPciture(this, mTempFile.getAbsolutePath());

            }
        } else if (requestCode == 551) {
            if (resultCode == RESULT_OK) {
                if (intent != null) {
                    //获取选择器返回的数据
                    ArrayList<String> images = intent.getStringArrayListExtra(
                            ImageSelectorUtils.SELECT_RESULT);
                    Log.e("=====361", "====" + images.get(0));
                    CameraUtil.flushPciture(this, images.get(0));
                }
            }
        }
    }

    @OnClick({R.id.ib_back, R.id.testButton, R.id.maskButton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.testButton:
                mKProgressHUD.setLabel(getResources().getString(R.string.testing)).show();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mKProgressHUD.isShowing()) {
                            mKProgressHUD.dismiss();
                        }
                    }
                }, 7000);
                testWater();

                break;
            case R.id.maskButton:
                try {
                    String name = (String) SPUtil.get(activity, deviceId, "", "mLastCourseName");
                    if (name.equals("")) {
                        mLastCourseName = "";
                    } else {
                        mLastCourseName = MyApplication.getCourseFromIndex(Integer.parseInt(name));
                    }
                } catch (Exception e) {
                    mLastCourseName = (String) SPUtil.get(activity, deviceId, "", "mLastCourseName");
                }
                mLimitCourseCount = (int) SPUtil.get(activity, deviceId, 0, "LimitCourseCount");


                if (!MyApplication.isCourseExist) {
                    new AlertDialog.Builder(activity).setTitle(R.string.course_data_no_exit_title)
                            .setMessage(R.string.course_data_no_exit_message)
                            .setPositiveButton(R.string.ok, null)
                            .show();
                } else {
                    if (mLastCourseName == "") {
                        startCourse();
                    } else {
                        if (MyApplication.selectCourse.getName().equals(mLastCourseName)) {
                            startCourse();
                        } else if (mLimitCourseCount >= Contants.LIMIT_COURSE_COUNT || mLimitCourseCount == 0) {
                            startCourse();
                        } else {
                            new AlertDialog.Builder(activity).setTitle(R.string.course_count_no_six_title)
                                    .setMessage(getResources().getString(R.string.cycle_message1) + mLastCourseName +
                                            getResources().getString(R.string.cycle_message2) + mLimitCourseCount + getResources().getString(R.string.cycle_message3))
                                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            changeHomeFragmentUi();
                                        }
                                    })
                                    .show();
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void setWaterData(BleDevice bleDevice, byte[] buffer) {
        super.setWaterData(bleDevice, buffer);
        Double voltage = (buffer[4] & 0xff) / 255.0 * 3;
        int time = (buffer[8] & 0xff);
        Log.e("gatt", "onServicesDiscovered: " + voltage + "=========" + time);
        //进度条  会出现 0 的时候没有值的情况
        if (mKProgressHUD == null) {
            return;
        }
        if (time > 0) {
            if (mTestData == null) {
                mTestData = new ArrayList<>();
            }
            if (voltage > 0.1) {
                mTestData.add(voltage);
            }
            if (!mKProgressHUD.isShowing()) {
                mKProgressHUD.show();
            }
        } else {
            mKProgressHUD.dismiss();
            Double total = 0.0;
            for (Double data : mTestData) {
                total += data;
            }
            voltage = total / mTestData.size();
            Log.e("====voltage====", voltage + "====");
            mTestData.clear();
            Double water;
            if (voltage >= 0.1 && voltage <= 0.3) {
                water = (voltage - 0.1) / 0.02 + 20;
            } else if (voltage > 0.3 && voltage <= 0.8) {
                water = (voltage - 0.3) / 0.05 + 30;
            } else if (voltage > 0.8 && voltage <= 2.2) {
                water = (voltage - 0.8) / 0.14 + 40;
            } else if (voltage > 2.2 && voltage < 3.0) {
                water = (voltage - 2.2) / 0.08 + 50;
            } else if (voltage == 3.0) {
                water = 60 + Math.random() * 10;
            } else {
                builder = new AlertDialog.Builder(TestWaterActivity.this).setTitle(R.string.test_error_title)
                        .setMessage(R.string.test_error_message)
                        .setPositiveButton(R.string.ok, null);
                builder.show();
                waterTextView.setText("10%");
                waterIamgeView.setImageResource(getIamgeResource(10, true));
                oilTextView.setText("10%");
                oilImageView.setImageResource(getIamgeResource(10, false));
                return;
            }
            mMaskButton.setVisibility(View.VISIBLE);
            final int fWater = water.intValue();
            waterTextView.setText(fWater + "%");
            waterIamgeView.setImageResource(getIamgeResource(fWater, true));

            Double fat = 0.0;//油
            if (water < 34) {
                fat = (water - 22.1) * 1.5 + 33.15 - 10;
            } else if (water >= 34 && water < 50) {
                fat = (water - 34) * 2 / 3.0 + 22.70;
            } else if (water >= 50 && water < 60) {
                fat = (water - 50) * 0.3 + 16;
            } else if (water >= 60) {
                fat = 10.0;
            }
            final int fFat = fat.intValue();
            oilTextView.setText(fFat + "%");
            oilImageView.setImageResource(getIamgeResource(fFat, false));
            final String beforeDate = BlEUtile.current();
            SPUtil.put(this, "lastTestTime", beforeDate, "lastTestTime");

            //保存数据库
            BeforeCourseData beforeCourseData = new BeforeCourseData(beforeDate, fWater, fFat);
            beforeCourseData.setName("油水测试");
            beforeCourseData.setCoursedate("A");
            beforeCourseData.setIsUpNet(isNetworkConnected(this) ? "1" : "0");
            BeforeCourseData.save(beforeCourseData);

            BeforeCourseData beforeCourseData1 = new BeforeCourseData(beforeDate, fWater, fFat);
            beforeCourseData1.setName(MyApplication.selectCourse.getName());
            BeforeCourseData.save(beforeCourseData1);
            MyApplication.isTestWater = true;

            if (mOkhttpUtils == null) {
                mOkhttpUtils = new OkhttpUtils(this, Contants.INSERT_BEFAT1, new OkListener() {
                    @Override
                    public void onSuccess(int requestCode, String string) {

                    }

                    @Override
                    public void onError(int requestCode, IOException e) {
                    }
                });
            }
            mMap1.clear();

            mMap1.put("name", "油水测试");
            mMap1.put("coursedate", "A");
            mMap1.put("deviceid", LocationUtil.getUniquePsuedoID());
            mMap1.put("beforedate", beforeDate);
            mMap1.put("beforefwater", fWater);
            mMap1.put("beforeffat", fFat);
            mMap1.put("address", Utils.getCurMac());
            mMap1.put("islogo", "A");
            Timber.d("做面膜前测油水数据：beforefwater：" + fWater + "---beforeffat：" + fFat);
            mOkhttpUtils.postForm(Contants.INSERT_BEFAT1, Contants.BASE_URL + INSERT_BEFAT, mMap1);
        }
    }

    private void changeHomeFragmentUi() {
        EventBus.getDefault().post(new MessageEvent("changeHomeUi", 600));
        Intent intent = new Intent("jerry");
        intent.putExtra("change", "yes");
        intent.putExtra("mLastCourseName", mLastCourseName);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        finish();
    }

    private void startCourse() {
        final BleDevice bleDevice = Utils.getFirstDevice();
        if (bleDevice == null) return;
        if (MyApplication.bluetoothState == Contants.STATE_NO_RUN) {
            if (MyApplication.isTestWater) {
                StartCourseActivity.startAct(activity, bleDevice);
                finish();
            } else {
                new AlertDialog.Builder(activity).setTitle(R.string.start_dialog_title)
                        .setMessage(R.string.start_dialog_message)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                TestWaterActivity.startAct(activity, bleDevice);
                            }
                        })
                        .show();
            }
        } else if (MyApplication.selectCourse.equals(MyApplication.runningCourse)) {
            StartCourseActivity.startAct(activity, bleDevice);
            finish();
        } else {
            new AlertDialog.Builder(activity).setTitle(R.string.other_course_run_title)
                    .setMessage(R.string.other_course_run_message)
                    .setNegativeButton(R.string.other_course_run_negative_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            StartCourseActivity.startAct(activity, bleDevice);
                            finish();
                        }
                    })
                    .setPositiveButton(R.string.other_course_run_positive_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Log.e("ceshi", "startCourse: " + MyApplication.selectCourse);
                            startNewCourse(bleDevice);
                        }
                    })
                    .show();
        }
    }

    private void startNewCourse(final BleDevice bleDevice) {
        //先停止 正在运行的课程
        if (MyApplication.isTestWater) {
            bleStopCourse();
        } else {
            new AlertDialog.Builder(activity).setTitle(R.string.start_dialog_title)
                    .setMessage(R.string.start_dialog_message)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TestWaterActivity.startAct(activity, bleDevice);
                        }
                    })
                    .show();
        }
    }

    private void bleStopCourse() {
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getStopCourseCommand(), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    StartCourseActivity.startAct(activity, bleDevice);
                    finish();
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }


    public static void startAct(Context context, BleDevice bleDevice) {
        Intent intent = new Intent(context, TestWaterActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.BLE_DEVICE, bleDevice);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}
